package com.vq.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.vq.common.Code;
import com.vq.entity.User;
import com.vq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    TrendsService trendsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 通过ID转换为账号
     * @param account
     * @return
     */
    String getAccount(Long account) {
        String str = account.toString();
        StringBuilder acc = new StringBuilder();
        for (int i = 1; i < 12-str.length(); i++) {
            acc.insert(0,"0");
        }
        acc.append(str);
        return acc.toString();
    }

    /**
     * 添加
     */
    public Integer insert(User user) {
        //判断是否为null
        if (user.getUsername() == null||user.getPassword() == null) {
            return 0;
        }
        //判断是否为空
        if ("".equals(user.getUsername())||"".equals(user.getPassword())) {
            return 0;
        }
        //判断该邮箱是否已经存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail, user.getEmail());
        User user1 = userMapper.selectOne(lqw);
        if (user1!=null) return Code.EMAIL_ALREADY_EXISTS;
        //添加账户
        user.setId(userMapper.selectToMaxId()+1);
        user.setAccount(getAccount(user.getId()));
        user.setPassword(passwordEncoder.encode(user.getPassword()));//加密密码
        int i = userMapper.insert(user);
        return i==1?1:0;
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 搜素用户
     */
    public List<User> search(String username) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(User::getUsername, username);
        return userMapper.selectList(lqw);
    }
    /**
     * 查询所有
     */
    public List<User> selectAll() {
        return userMapper.selectList(null);
    }
    /**
     * 查询id对应的用户
     * @param bo 是否需要密码
     */
    public User selectById(Long id, boolean bo) {
        User user = userMapper.selectById(id);
        if(user!=null&&!bo) {
            user.setPassword("");
        }
        return user;
    }
    /**
     * 查询是否账号存在
     * @param account 通过账号查询
     * @param bo 是否需要密码
     * @return
     */
    public User selectByAccount(String account, boolean bo) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getAccount, account);
        User user = userMapper.selectOne(lqw);
        //如果账号不为空，并且为false，则置空密码
        if(user!=null&&!bo) {
            user.setPassword("");
        }
        return user;
    }
    /**
     * 查询是否邮箱存在
     * @param email
     * @param bo 是否需要密码
     * @return
     */
    public User selectToEmail(String email, boolean bo) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail, email);
        User user = userMapper.selectOne(lqw);
        //如果账号不为空，并且为false，则置空密码
        if(user!=null&&!bo) {
            user.setPassword("");
        }
        return user;
    }
    /**
     * 根据账号密码或者邮箱密码查询
     */
    public User selectToAccPas(String accountOrEmail, String password) {
        if (accountOrEmail==null||password==null||accountOrEmail.equals("")||password.equals("")) return null;
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getAccount, accountOrEmail);
        User user = userMapper.selectOne(lqw);
        //如果账号查询为空，再以邮箱查询
        if (user==null) {
            lqw.clear();
            lqw.eq(User::getEmail, accountOrEmail);
            user = userMapper.selectOne(lqw);
        }
        //判断密码是否与加密的密码相同
        if (user!=null&&passwordEncoder.matches(password, user.getPassword())) return user;
        return null;
    }

    /**
     * 修改
     */
    public boolean updateById(User user) {
        if (user==null) return false;//修改用户为空
        User myUser = userMapper.selectById(user.getId());
        if (myUser==null) return false;//该用户不存在
        if (!passwordEncoder.matches(user.getPassword(), myUser.getPassword())) return false;
        LambdaUpdateWrapper<User> luw = new LambdaUpdateWrapper<>();
        //对指定id的用户只修改 用户名
        luw.eq(User::getId, user.getId()).set(User::getUsername, user.getUsername());
        //修改
        return userMapper.update(user, luw)==1;
    }
    /**
     * 修改密码
     * @param id 需要修改账户的id
     * @param oldPassword 账户旧密码
     * @param newPassword 账户新密码
     * @param bo 是否直接修改密码
     * @return
     */
    public boolean updateToPasswordById(Long id, String oldPassword, String newPassword, boolean bo) {
        User myUser = userMapper.selectById(id);
        //如果与原密码相同，直接返回
        if (passwordEncoder.matches(newPassword, myUser.getPassword())) return true;
        //判断密码是否相等（如果bo为true则无需密码相等）
        if (bo||passwordEncoder.matches(oldPassword, myUser.getPassword())) {
            //将密码加密并修改
            myUser.setPassword(passwordEncoder.encode(newPassword));
            //修改密码
            return userMapper.updateById(myUser)==1;
        }
        else {
            return false;
        }
    }
    /**
     * 增加关注量
     */
    public boolean appendFollowersNum(Long id) {
        User user = this.selectById(id, true);
        if (user==null) return false;
        user.setFollowersNum(Math.max(user.getFollowersNum()+1,0));
        return userMapper.updateById(user)==1;
    }
    /**
     * 减少关注量
     */
    public boolean reduceFollowersNum(Long id) {
        User user = this.selectById(id, true);
        if (user==null) return false;
        user.setFollowersNum(Math.max(user.getFollowersNum()-1, 0));
        return userMapper.updateById(user)==1;
    }
    /**
     * 增加粉丝量
     */
    public boolean appendFansNum(Long id) {
        User user = this.selectById(id, true);
        if (user==null) return false;
        user.setFansNum(Math.max(user.getFansNum()+1,0));
        return userMapper.updateById(user)==1;
    }
    /**
     * 减少粉丝量
     */
    public boolean reduceFansNum(Long id) {
        User user = this.selectById(id, true);
        if (user==null) return false;
        user.setFansNum(Math.max(user.getFansNum()-1,0));
        return userMapper.updateById(user)==1;
    }
}
